<template>
  <div class="category-products-page">
    <div class="i_bg">
      <div class="postion">
        <span class="fl">全部 > 搜索结果 > </span>
      </div>
      
      <!--Begin 筛选条件 Begin-->
      <div class="content mar_10">
        <table border="0" class="choice" style="width:100%; font-family:'宋体'; margin:0 auto;" cellspacing="0" cellpadding="0">
          <tbody>
            <!-- <tr valign="top">
              <td>&nbsp; 排序：</td>                                                                                                       
              <td class="td_a">
                <a href="#" :class="{ 'now': sortOption === 'default' }" @click.prevent="handleSortChange('default')">默认</a>
                <a href="#" :class="{ 'now': sortOption === 'price-asc' }" @click.prevent="handleSortChange('price-asc')">价格↑</a>
                <a href="#" :class="{ 'now': sortOption === 'price-desc' }" @click.prevent="handleSortChange('price-desc')">价格↓</a>
              </td>
            </tr> -->
            <tr valign="top">
              <td>&nbsp; 价格：</td>                                                                                                       
              <td class="td_a">
                <a href="#" v-for="(price, index) in prices" :key="index" :class="{ 'now': selectedPrice === price }" @click.prevent="selectPrice(price)">
                  {{ price }}
                </a>
              </td>
            </tr>                                             
          </tbody>
        </table>                                                                                 
      </div>
      <!--End 筛选条件 End-->
      
      <div class="content mar_20">
        <!-- 添加调试信息
        <div v-if="true" style="color: red; margin: 10px 0; padding: 10px; background-color: #f0f0f0; border-radius: 5px;">
          调试信息: 搜索关键字 = "{{ searchKeyword }}" | 商品数量 = {{ productList.length }}
        </div> -->
        
        <div class="l_history">
          <div class="his_t">
            <span class="fl">浏览历史</span>
            <span class="fr"><a href="#">清空</a></span>
          </div>
          <ul>
            <li>
              <div class="img"><a href="#"><img src="@/assets/images/his_1.jpg" width="185" height="162" /></a></div>
              <div class="name"><a href="#">Dior/迪奥香水2件套装</a></div>
              <div class="price">
                <font>￥<span>368.00</span></font> &nbsp; 18R
              </div>
            </li>
            <li>
              <div class="img"><a href="#"><img src="@/assets/images/his_2.jpg" width="185" height="162" /></a></div>
              <div class="name"><a href="#">Dior/迪奥香水2件套装</a></div>
              <div class="price">
                <font>￥<span>768.00</span></font> &nbsp; 18R
              </div>
            </li>
            <li>
              <div class="img"><a href="#"><img src="@/assets/images/his_3.jpg" width="185" height="162" /></a></div>
              <div class="name"><a href="#">Dior/迪奥香水2件套装</a></div>
              <div class="price">
                <font>￥<span>680.00</span></font> &nbsp; 18R
              </div>
            </li>
            <li>
              <div class="img"><a href="#"><img src="@/assets/images/his_4.jpg" width="185" height="162" /></a></div>
              <div class="name"><a href="#">Dior/迪奥香水2件套装</a></div>
              <div class="price">
                <font>￥<span>368.00</span></font> &nbsp; 18R
              </div>
            </li>
            <li>
              <div class="img"><a href="#"><img src="@/assets/images/his_5.jpg" width="185" height="162" /></a></div>
              <div class="name"><a href="#">Dior/迪奥香水2件套装</a></div>
              <div class="price">
                <font>￥<span>368.00</span></font> &nbsp; 18R
              </div>
            </li>
          </ul>
        </div> 

        <div class="l_list">
          <div class="list_t">
            <span class="fl list_or">
              <a href="#" :class="{ 'now': sortOption === 'default' }" @click.prevent="handleSortChange('default')">默认</a>
              <a href="#" :class="{ 'now': sortOption === 'sales' }" @click.prevent="handleSortChange('sales')">
                <span class="fl">销量</span>                        
                <span class="i_up">销量从低到高显示</span>
                <span class="i_down">销量从高到低显示</span>                                                     
              </a>
              <a href="#" :class="{ 'now': sortOption === 'price-asc' }" @click.prevent="handleSortChange('price-asc')">
                <span class="fl">价格</span>                        
                <span class="i_up">价格从低到高显示</span>
                <span class="i_down">价格从高到低显示</span>     
              </a>
              <a href="#" :class="{ 'now': sortOption === 'new' }" @click.prevent="handleSortChange('new')">新品</a>
            </span>
            <span class="fr">共发现{{ pagination.total }}件</span>
          </div>

          <div class="list_c">
            
            <!-- 商品列表 -->
            <div class="product-list" v-loading="loading">
              <div v-if="!loading && productList && productList.length > 0">
                <ul class="cate_list">
                  <li v-for="product in productList" :key="product.id">
                    <div class="img">
                      <a href="#" @click.prevent="viewProduct(product.id)">
                        <img :src="getProductImage(product)" :alt="product.name" width="210" height="185" @error="handleImageError" />
                      </a>
                    </div>
                    <div class="price">
                      <font>￥<span>{{ product.price }}</span></font> &nbsp; {{ product.sales || 0 }}R
                    </div>
                    <div class="name">
                      <a href="#" @click.prevent="viewProduct(product.id)" v-html="highlightKeyword(product.name)"></a>
                    </div>
                    <!-- 添加商品描述并高亮关键字 -->
                    <!-- <div class="description" v-if="product.description" v-html="highlightKeyword(product.description)"></div> -->
                    <div class="carbg">
                      <a href="#" class="ss" @click.prevent="addToFavorites(product)">
                        <span v-if="isProductFavorited(product.id)">已收藏</span>
                        <span v-else>收藏</span>
                      </a>
                      <a href="#" class="j_car" @click.prevent="addToCart(product)">加入购物车</a>
                    </div>
                  </li>
                </ul>
              </div>
              
              <!-- 无搜索结果 -->
              <div v-if="!loading && searchKeyword && productList.length === 0" class="no-products">
                <el-empty description="暂无相关商品" />
              </div>
              
              <!-- 未搜索状态 -->
              <div v-if="!loading && !searchKeyword" class="no-products">
                <el-empty description="请输入关键词搜索商品" />
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pages" v-if="totalPages > 1">
              <a href="#" class="p_pre">上一页</a><a href="#" class="cur">1</a><a href="#">2</a><a href="#">3</a>...<a href="#">20</a><a href="#" class="p_pre">下一页</a>
            </div>
          </div>
        </div>
      </div>
      
      <!-- <div style="margin-top: 20px; margin-bottom: 20px; text-align: center;">
        <router-link to="/" class="btn btn-primary">返回首页</router-link>
      </div> -->
    </div>
  </div>
</template>

<script>
import { queryProduct } from '@/api/productApi'
import { addToCart } from '@/api/cartApi'
import { addFavorite, removeFavorite, getFavorites, getFavoriteItems, createFavorite } from '@/api/favoriteApi'

export default {
  name: 'SearchResults',
  data() {
    return {
      searchKeyword: '',
      productList: [],
      pagination: {
        current: 1,
        size: 20,
        total: 0
      },
      sortOption: 'default',
      loading: false,
      selectedPrice: '', // 添加价格筛选
      prices: ['0-199', '200-399', '400-599', '600-899', '900-1299', '1300-1399', '1400以上'], // 添加价格区间
      userId: '',
      isLoggedIn: false,
      favoriteItems: [], // 存储当前用户的收藏商品
      defaultCollectId: ''
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.pagination.total / this.pagination.size)
    },
    pageNumbers() {
      const pages = []
      const total = this.totalPages
      const current = this.pagination.current
      let start = Math.max(1, current - 2)
      let end = Math.min(total, current + 2)
      
      if (end - start < 4) {
        if (start === 1) {
          end = Math.min(total, start + 4)
        } else {
          start = Math.max(1, end - 4)
        }
      }
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      
      return pages
    }
  },
  watch: {
    // 监听路由变化，当搜索关键字改变时重新搜索
    '$route.query.keyword': {
      handler(newKeyword) {
        this.searchKeyword = newKeyword || ''
        this.pagination.current = 1
        if (this.searchKeyword) {
          this.fetchProductList()
        } else {
          this.productList = []
          this.pagination.total = 0
        }
      },
      immediate: true
    },
    // 监听路由参数变化
    '$route'(to, from) {
      // 从查询参数中获取搜索关键词
      const keyword = to.query.keyword
      if (keyword && keyword !== this.searchKeyword) {
        this.searchKeyword = keyword
        this.pagination.current = 1
        this.fetchProductList()
      }
    }
  },
  methods: {
    // 转义正则表达式特殊字符
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    },
    
    // 转义HTML特殊字符
    escapeHtml(text) {
      if (!text) return '';
      const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      };
      return text.replace(/[&<>"']/g, m => map[m]);
    },
    
    // 高亮显示搜索关键字（最终版实现）
    highlightKeyword(text) {
      // 如果没有搜索关键词或文本为空，直接返回原文本
      if (!this.searchKeyword || !text) {
        return text;
      }
      
      // 获取搜索关键词
      const keyword = this.searchKeyword.trim();
      
      // 如果关键词为空，返回原文本
      if (!keyword) {
        return text;
      }
      
      try {
        // 转义正则表达式特殊字符
        const escapedKeyword = this.escapeRegExp(keyword);
        
        // 创建正则表达式，忽略大小写，全局匹配
        const regex = new RegExp(`(${escapedKeyword})`, 'gi');
        
        // 使用replace方法替换匹配的关键词，添加高亮标签
        const result = text.replace(regex, '<span style="background-color: #ffeb3b; font-weight: bold; padding: 2px 4px; border-radius: 3px;">$1</span>');
        
        return result;
      } catch (error) {
        console.error('高亮处理出错:', error);
        return text;
      }
    },
    
    // 获取商品列表
    async fetchProductList() {
      if (!this.searchKeyword) return
      
      this.loading = true
      try {
        const params = {
          keyword: this.searchKeyword,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size,
          sortBy: this.sortOption
        }
        
        // 添加价格筛选参数
        if (this.selectedPrice) {
          params.priceRange = this.selectedPrice
        }
        
        const res = await queryProduct(params)
        console.log('商品搜索结果:', res)
        
        // 根据后端接口返回的数据格式处理
        if (Array.isArray(res)) {
          // 直接使用返回的数组
          this.productList = res.map(product => ({
            id: product.id || '',
            name: product.name || '未知商品',
            price: product.price || 0,
            stock: product.stock || 0,
            fileName: product.fileName || '',
            description: product.description || '',
            sales: product.sales || product.saleCount || 0,
            ...product
          }));
          this.pagination.total = res.length;
        } else if (res && res.data && Array.isArray(res.data)) {
          // 如果数据在data字段中
          this.productList = res.data.map(product => ({
            id: product.id || '',
            name: product.name || '未知商品',
            price: product.price || 0,
            stock: product.stock || 0,
            fileName: product.fileName || '',
            description: product.description || '',
            sales: product.sales || product.saleCount || 0,
            ...product
          }));
          this.pagination.total = res.data.length;
        } else if (res && typeof res === 'object' && res !== null) {
          // 检查对象中是否有商品数组
          let foundProducts = false;
          
          // 遍历对象的所有属性
          for (const key in res) {
            if (Array.isArray(res[key]) && res[key].length > 0 && 
                typeof res[key][0] === 'object' && res[key][0] !== null &&
                (res[key][0].id || res[key][0].name)) {
              this.productList = res[key].map(product => ({
                id: product.id || '',
                name: product.name || '未知商品',
                price: product.price || 0,
                stock: product.stock || 0,
                fileName: product.fileName || '',
                description: product.description || '',
                sales: product.sales || product.saleCount || 0,
                ...product
              }));
              this.pagination.total = res[key].length;
              foundProducts = true;
              break;
            }
          }
          
          if (!foundProducts) {
            // 其他情况，设置为空数组
            this.productList = [];
            this.pagination.total = 0;
          }
        } else {
          // 其他情况，设置为空数组
          this.productList = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        console.error('搜索商品失败:', error)
        this.$message.error('搜索商品失败: ' + (error.message || '未知错误'))
        this.productList = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    
    // 查看商品详情
    viewProduct(productId) {
      this.$router.push({ name: 'ProductDetail', params: { id: productId } })
    },
    
    // 检查用户登录状态
    checkLoginStatus() {
      const userInfo = localStorage.getItem('userInfo')
      this.isLoggedIn = !!userInfo
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          this.userId = user.id || user.userId || ''
        } catch (e) {
          console.error('解析用户信息失败:', e)
          localStorage.removeItem('userInfo')
        }
      }
    },
    
    // 获取用户的收藏夹数据
    async loadFavoriteData() {
      if (!this.isLoggedIn || !this.userId) return
      
      try {
        // 获取用户的收藏夹
        const collectsResponse = await getFavorites(this.userId)
        const collects = Array.isArray(collectsResponse) ? collectsResponse : collectsResponse.data || []
        
        // 查找默认收藏夹
        const defaultCollect = collects.find(collect => collect.name === '默认收藏夹')
        if (defaultCollect) {
          this.defaultCollectId = defaultCollect.id
        } else if (collects.length > 0) {
          // 如果没有默认收藏夹，使用第一个收藏夹
          this.defaultCollectId = collects[0].id
        }
        
        // 获取默认收藏夹中的商品
        if (this.defaultCollectId) {
          const itemsResponse = await getFavoriteItems(this.userId, this.defaultCollectId)
          this.favoriteItems = Array.isArray(itemsResponse) ? itemsResponse : itemsResponse.data || []
        }
      } catch (error) {
        console.error('加载收藏夹数据失败:', error)
        this.$message.error('加载收藏夹数据失败: ' + (error.message || '未知错误'))
      }
    },
    
    // 检查商品是否已收藏
    isProductFavorited(productId) {
      return this.favoriteItems.some(item => item.productId === productId)
    },
    
    // 添加到收藏
    async addToFavorites(product) {
      // 检查登录状态
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }
      
      // 确保已获取收藏夹信息
      if (!this.defaultCollectId) {
        await this.loadFavoriteData()
      }
      
      // 如果仍未获取到默认收藏夹ID，则创建默认收藏夹
      if (!this.defaultCollectId) {
        try {
          await createFavorite(this.userId, '默认收藏夹')
          await this.loadFavoriteData()
        } catch (error) {
          console.error('创建默认收藏夹失败:', error)
          this.$message.error('创建默认收藏夹失败')
          return
        }
      }
      
      try {
        // 检查商品是否已收藏
        const isFavorited = this.isProductFavorited(product.id)
        
        if (isFavorited) {
          // 如果已收藏，则取消收藏
          await removeFavorite(this.userId, product.id, this.defaultCollectId)
          // 从本地列表中移除
          this.favoriteItems = this.favoriteItems.filter(item => item.productId !== product.id)
          this.$message.success('已取消收藏')
        } else {
          // 如果未收藏，则添加收藏
          await addFavorite(this.userId, product.id, this.defaultCollectId)
          // 添加到本地列表
          const favoriteItem = {
            productId: product.id,
            productName: product.name,
            productImage: product.fileName || ''
          }
          this.favoriteItems.push(favoriteItem)
          this.$message.success('已添加到收藏夹')
        }
        
        // 通知全局收藏夹组件更新
        window.dispatchEvent(new Event('favorite-updated'))
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$message.error('操作失败: ' + (error.message || '网络错误'))
      }
    },
    
    // 添加到购物车
    async addToCart(product) {
      try {
        // 构造购物车项目数据
        const cartItem = {
          productId: product.id.toString(),
          productName: product.name,
          quantity: 1, // 默认数量为1
          price: parseFloat(product.price),
          image: product.fileName || ''
        };

        // 调用API添加到购物车
        const res = await addToCart(cartItem);
        
        // 检查响应结果
        if (res === 'success') {
          this.$message.success(`已添加到购物车: ${product.name}`);
          // 触发全局购物车更新事件
          window.dispatchEvent(new Event('cart-updated'));
        } else {
          this.$message.error(res.message || '加入购物车失败');
        }
      } catch (error) {
        console.error('添加购物车失败:', error);
        this.$message.error('添加购物车失败: ' + (error.message || '网络错误'));
      }
    },
    
    // 处理排序变化
    handleSortChange(value) {
      this.sortOption = value
      this.pagination.current = 1
      this.fetchProductList()
    },
    
    // 选择价格区间
    selectPrice(price) {
      this.selectedPrice = this.selectedPrice === price ? '' : price
      this.pagination.current = 1
      this.fetchProductList()
    },
    
    // 上一页
    prevPage() {
      if (this.pagination.current > 1) {
        this.pagination.current--
        this.fetchProductList()
      }
    },
    
    // 下一页
    nextPage() {
      if (this.pagination.current < this.totalPages) {
        this.pagination.current++
        this.fetchProductList()
      }
    },
    
    // 跳转到指定页
    goToPage(page) {
      if (page !== this.pagination.current) {
        this.pagination.current = page
        this.fetchProductList()
      }
    },
    
    // 获取商品图片
    getProductImage(product) {
      // 确保 product 对象存在
      if (!product) {
        return require('@/assets/images/default_product.jpg');
      }
      
      // 检查是否有 fileName 字段
      if (product.fileName) {
        try {
          // 先尝试从 assets/files 目录加载
          const imageModule = require(`@/assets/files/${product.fileName}`);
          return imageModule;
        } catch (error) {
          // 如果图片不存在，尝试从 public/images 目录加载
          try {
            const imageModule = require(`@/assets/images/${product.fileName}`);
            return imageModule;
          } catch (secondError) {
            // 如果都不存在，返回默认图片
            console.warn(`商品图片加载失败: ${product.fileName}`, error);
          }
        }
      }
      
      // 如果没有fileName或加载失败，返回默认图片
      try {
        return require('@/assets/images/default_product.jpg');
      } catch (error) {
        console.error('默认图片加载失败:', error);
        return ''; // 返回空字符串作为最后的备选方案
      }
    },
    
    // 处理图片加载错误
    handleImageError(event) {
      console.log('图片加载错误，尝试使用默认图片');
      try {
        event.target.src = require('@/assets/images/default_product.jpg');
      } catch (error) {
        console.error('默认图片加载失败:', error);
        // 如果默认图片也加载失败，设置为空白图片
        event.target.src = '';
      }
    }
  },
  
  // 在组件创建时检查登录状态并加载收藏数据
  created() {
    this.checkLoginStatus()
    if (this.isLoggedIn) {
      this.loadFavoriteData()
    }
  }
}
</script>

<style scoped>
@import '@/assets/css/easybuy-style.css';

/* 保留原有的样式，以确保功能正常 */
.product-list {
  min-height: 300px;
}

/* 添加高亮样式 */
.highlight {
  background-color: #ffeb3b !important;
  color: #333 !important;
  font-weight: bold !important;
  padding: 2px 4px !important;
  border-radius: 3px !important;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1) !important;
}

.no-products {
  text-align: center;
  padding: 40px 0;
}
</style>